package com.csdj.x315springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csdj.x315springboot.common.CacheConstant;
import com.csdj.x315springboot.entity.User;
import com.csdj.x315springboot.mapper.UserMapper;
import com.csdj.x315springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.x315springboot.service.RedisService;
import com.csdj.x315springboot.util.EncryptUtil;
import com.csdj.x315springboot.util.RandomUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cloud
 * @since 2021-12-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisService redisService;

    @Override
    public User login(String username, String password) {
        String depass = EncryptUtil.sha256(password);
        if(StringUtils.isNotBlank(depass)){
            QueryWrapper<User> query = new QueryWrapper<>();
            query.lambda().eq(User::getUsername,username)
                    .eq(User::getPassword,depass);
            User user = getOne(query);
            if(user != null){
                //不返回密码给前端
                user.setPassword("");
                user.setToken(RandomUtil.genToken());
                //将token保存到redis
                redisService.set(CacheConstant.TOKEN_PREFIX+user.getId(),user.getToken());
            }
            return user;
        }
        return null;
    }

    @Override
    public IPage<User> getByPage(int page, int rows) {
        IPage<User> iPage = new Page<>(page,rows);
        iPage = userMapper.selectPage(iPage, null);
        return iPage;
    }
}
